package BM.test;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.Toast;

public class BatteryAppWidgetProvider extends AppWidgetProvider {
	private static final String UPDATE_ACTION = "BM.test.BatteryAppWidgetProvider.UPDATE_APP_WIDGET";
	public static final String UPDATE_Battery_ACTION = "BM.test.BatteryAppWidgetProvider.UPDATE_Battery_ACTION";
	private static Bundle batteryInfo;

	@Override
	public void onDisabled(Context context) {
		context.stopService(new Intent(context, BatteryManagementService.class));
	}

	@Override
	public void onEnabled(Context context) {
		context.startService(new Intent(context, BatteryManagementService.class));
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
		String action = intent.getAction();
		if (UPDATE_ACTION.equals(action)) {
			if (batteryInfo != null) {
				double v=batteryInfo.getInt("voltage", 0)/1000.0;
				double temp=batteryInfo.getInt("temperature", 0)/10.0;
				String health = "未知";
				switch(batteryInfo.getInt("health",0)){
				case BatteryManager.BATTERY_HEALTH_UNKNOWN:
					health="未知";
					break;
				case BatteryManager.BATTERY_HEALTH_GOOD:
					health="良好";
					break;
				case BatteryManager.BATTERY_HEALTH_OVERHEAT:
					health="过热";
					break;
				case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
					health="过电压";
					break;
				case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
					health="未指定错误";
					break;
				}
				Toast.makeText(context,
						"电压：" + v + "V\n温度：" + temp+"°\n健康程度："+health, 1).show();
			}
		} else if (UPDATE_Battery_ACTION.equals(action)) {
			BatteryAppWidgetProvider.batteryInfo=intent.getExtras();
		}
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		context.startService(new Intent(context, BatteryManagementService.class));
		// 创建一个Intent对象
		Intent intent = new Intent();
		// 为Intent对象设置Action
		intent.setAction(UPDATE_ACTION);
		// 使用getBroadcast方法，得到一个PendingIntent对象，当该对象执行时，会发送一个广播
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
				intent, 0);
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
				R.layout.appwidget);
		remoteViews.setOnClickPendingIntent(R.id.imageId, pendingIntent);
		appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
	}
}
